<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商户名称">
          <el-input v-model="searchForm.merchantName" placeholder="请输入商户名称" clearable class="w-60" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px"
            v-has="'shop:merchantReport:save'">新增报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="merchantId" label="商铺ID" />
      <el-table-column prop="merchantName" label="商铺名称" />
      <el-table-column prop="filePath" label="报表存储路径" />
      <el-table-column prop="submitTime" label="提交时间" width="170" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="text" v-has="'shop:merchantReport:update'" @click="download(row)">下载</el-button>
          <el-button type="text" v-has="'shop:merchantReport:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'shop:merchantReport:delete'"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增报表' : '编辑报表'" :visible.sync="dialogVisible" width="80%"
      @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="dialog_height">
        <el-form-item label="商铺名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商铺名称" />
        </el-form-item>
        <el-form-item label="品牌商铺" prop="merchantId">
          <el-select filterable  v-model="form.merchantId" placeholder="请选择品牌商铺" @change="handleMerchantChange" style="width: 100%">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="submitTime">
          <el-date-picker v-model="form.submitTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="请选择提交时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="附件">
          <!-- <el-input v-model="form.filePath" placeholder="请输入报表存储路径" /> -->
          <el-upload class="upload-demo" :headers="headers" :action="$uploadUrl" :file-list="fileList" :limit="1"
            :on-success="handleIconSuccess" :on-remove="handleRemove">
            <!-- <img v-if="formData.filePath" :src="formData.coverImage" class="uploaded-image" />
                        <div v-else class="upload-placeholder">
                          <i class="el-icon-plus"></i>
                          <div class="upload-text">点击上传封面图片</div>
                        </div> -->
            <el-button style="margin-left: 10px;" size="small" type="success"
              v-if="fileList.length === 0">点击上传附件</el-button>
          </el-upload>
        </el-form-item>
  
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MerchantList',
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        merchantName: '',
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      fileList: [],
      form: {
        merchantId: '',
        filePath: '',
        submitTime: '',
        merchantName: '',
      },
      // 表单校验规则
      rules: {
        id: [{ required: true, message: '请输入序号', trigger: 'blur' }],
        merchantName: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
        merchantId: [{ required: true, message: '请选择d品牌商铺', trigger: 'blur' }],
        filePath: [{ required: true, message: '请输入报表存储路径', trigger: 'blur' }],
      },
      merchantList: []
    }
  },
  created() {
    this.getList();
    this.queryUserList()
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = []
    },
    // 图片上传成功回调
    async handleIconSuccess(res) {
      console.log(res, 'res');
      this.fileList = [{
        url: res.result.filePath,
        name: res.result.filename
      }]
      console.log(res, 'res', this.fileList);
    },
    async queryUserList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      this.merchantList = data.result.records
      console.log(data, '商户列表');
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getMerchantReportList({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },
    handleMerchantChange(val) {
      console.log(val, '商户ID');
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        merchantName: '',
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },
    // 下载报表
    download(row) {
      this.$api.downloadReport(row.id).then(res => {
        console.log(res, '下载报表');
        // 创建一个隐藏的a标签来触发下载
        const link = document.createElement('a');
        link.href = res.data.result;
        link.setAttribute('download', '');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      // window.open(row.filePath, '_blank')
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      if (row.filePath) {
        const fileName = row.filePath.substring(row.filePath.lastIndexOf('/') + 1);
        this.fileList = [{
          url: row.filePath,
          name: fileName
        }]
      } else {
        this.fileList = []
      }
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteMerchantReport(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },


    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.fileList.length > 0) {
              this.form.filePath = this.fileList[0].url
            }
            if (this.form.filePath === '') {
              this.$message.error('请上传附件')
              return
            }
            if (this.dialogType === 'add') {
              await this.$api.addMerchantReport(this.form)
              this.$message.success('新增成功')
            } else {
              await this.$api.editMerchantReport(this.form)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        merchantId: '',
        filePath: '',
        submitTime: '',
        merchantName: '',
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height{
    height: 50vh;
    overflow: hidden;
    overflow-y: auto;
}
.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>